﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using Clipper.Model;
using Communication;
using Clipper.Model.EnumModel;
using Global;
using System.Collections.ObjectModel;
using Clipper.BLL.DetectChain.AddR1AndSample;
using static Clipper.Model.DataBaseModel.DisplayCup;

namespace Clipper.BLL.DetectChain
{
    /// <summary>
    /// 样本和加试剂1
    /// </summary>
    public class AddReagent1AndSample : ApplianceComponent
    {
        #region ---------成员变量,Anry-------

        private static Arm mArmSA = new Arm("SA", "5");                         // 样本臂A
        private static Arm mArmSB = new Arm("SB", "6");                         // 样本臂B
        private static Arm mArmR1A = new Arm("R1A", "7");                       // 试剂二臂A
        private static Arm mArmR1B = new Arm("R1B", "8");                       // 试剂二臂B
        private static Arm mArmSS = new Arm("SS", "14");                        // 样本系统
        private static Arm mArmDish1 = new Arm("TA", "7");                      // 试剂盘1
        private static ControlStatusEnum mStatusSA = ControlStatusEnum.IDLE;            // 样本臂A的状态
        private static ControlStatusEnum mStatusSB = ControlStatusEnum.IDLE;            // 样本臂B的状态
        private static ControlStatusEnum mStatusR1A = ControlStatusEnum.IDLE;           // 试剂二臂A的状态
        private static ControlStatusEnum mStatusR1B = ControlStatusEnum.IDLE;           // 试剂二臂B的状态
        private static ControlStatusEnum mStatusSS = ControlStatusEnum.IDLE;            // 样本系统的状态
        private static ControlStatusEnum mStatusDish1 = ControlStatusEnum.IDLE;         // 试剂盘1的状态

        private Arm mUsingSampleArm;                    // 正在使用的样本臂
        private Arm mUsingReagentArm;                   // 正在使用的试剂臂
        private ControlStatusEnum mStatusUsingSampleArm;    // 正在使用的样本臂状态
        private ControlStatusEnum mStatusUsingReagentArm;   // 正在使用的试剂臂状态

        private Clipper.DAL.DetectItems mDetectItem = new DAL.DetectItems();    // 检测项信息

        //public AddReagent1AndSample()
        //{
        //    mUsingSampleArm = mArmSA;
        //    mUsingReagentArm = mArmR1A;
        //}
        #endregion ---------成员变量----------------

        #region // --------属性,Anry-------

        /// <summary>
        /// 样本臂A
        /// </summary>
        public static Arm ArmSA
        {
            get { return mArmSA; }
            set { mArmSA = value; }
        }

        /// <summary>
        /// 样本臂B
        /// </summary>
        public static Arm ArmSB
        {
            get { return mArmSB; }
            set { mArmSB = value; }
        }

        /// <summary>
        /// 试剂臂A
        /// </summary>
        public static Arm ArmR1A
        {
            get { return mArmR1A; }
            set { mArmR1A = value; }
        }

        /// <summary>
        /// 试剂臂B
        /// </summary>
        public static Arm ArmR1B
        {
            get { return mArmR1B; }
            set { mArmR1B = value; }
        }

        /// <summary>
        /// 试剂盘1
        /// </summary>
        public static Arm ArmDish1
        {
            get { return mArmDish1; }
            set { mArmDish1 = value; }
        }
        #endregion // --------属性------------

        #region // 变量

        static ControlStatusEnum detectionStatus;
        static AutoResetEvent mPause = new AutoResetEvent(false);//暂停
        static ReactionCup mLastCup = null;//上一个反应杯
        static bool _isPause;
        static int mStripID;

        int mReagID;
        byte mHoleNum;
        private Clipper.DAL.Reagent mReagent = new DAL.Reagent();               // 试剂信息表
        private Clipper.DAL.ReagentKit mReagentKit = new DAL.ReagentKit();      // 试剂盘信息表

        static System.Timers.Timer mTimerCountDown = new System.Timers.Timer();//倒计时
        public static DateTime mdtInStart;
        static ObservableCollection<double> mTemperature;//试剂仓的温度
        #region 控制
        //试剂盘A
        public static ReagentKitControl Kit1 = new ReagentKitControl(Can.DW_R1_SA_ID, Can.R1A_Kit1_ID);
        /// <summary>
        /// 控制样本系统
        /// </summary>
        public static SampleControl Sample = new SampleControl();
        //样本臂SA
        public static ArmControl SA = new ArmControl(Can.DW_R1_SA_ID, Can.SA_MoveA_ID, "NA", "AA", "DA", "RA");
        //样本臂SB
        public static ArmControl SB = new ArmControl(Can.DW_R1_SA_ID, Can.SB_CupIn_ID, "NB", "AB", "DB", "RB");
        //试剂臂R1A
        public static ArmControl R1A = new ArmControl(Can.DW_R1_SA_ID, Can.R1A_Kit1_ID, "NC", "AD", "DD", "RC");
        /// <summary>
        /// 试剂臂R1B
        /// </summary>
        public static ArmControl R1B = new ArmControl(Can.DW_R1_SA_ID, Can.R1B_ID, "ND", "AE", "DF", "RD");

        /// <summary>
        /// 泵控制
        /// </summary>
        public static PumpControl PumpControl = new PumpControl();
        #endregion
        #endregion // 变量

        #region 属性
        /// <summary>
        /// 状态
        /// </summary>
        public override ControlStatusEnum DetectionStatus
        {
            get
            {
                return detectionStatus;
            }
            set
            {
                detectionStatus = value;
            }
        }
        /// <summary>
        /// 状态
        /// </summary>
        public static ControlStatusEnum Status
        {
            get
            {
                return detectionStatus;
            }
            set
            {
                detectionStatus = value;
            }
        }
        /// <summary>
        /// 获得或设置模块暂停状态
        /// </summary>
        public static bool IsPause
        {
            get
            {
                return _isPause;
            }
            //set
            //{
            //    _isPause = value;
            //    if (!_isPause)
            //    {
            //        mPause.Set();
            //    }
            //}
        }
        /// <summary>
        /// 上一个反应杯
        /// </summary>
        public static ReactionCup LastCup
        {
            get
            {
                return mLastCup;
            }
        }
        /// <summary>
        /// 试剂仓的温度，两个温度
        /// </summary>
        public static ObservableCollection<double> Temperature
        {
            get
            {
                if (mTemperature == null)
                {
                    mTemperature = new ObservableCollection<double>();
                }
                return mTemperature;
            }
            set
            {
                mTemperature = value;
            }
        }
        /// <summary>
        /// 温度平均值
        /// </summary>
        public static double TemperatureAVG
        {
            get
            {
                double total = 0;
                foreach (double _temp in Temperature)
                {
                    total += _temp;
                }
                return total / 2;
            }
        }
        /// <summary>
        /// 当前的条形码值
        /// </summary>
        public static string CurrentBarcode
        {
            get;
            set;
        }
        #endregion

        public AddReagent1AndSample()
        {
            //SA.Init(20, 10, 5,700,48,42);
            //SB.Init(13, 1, 28,110,38,35);
            //R1A.Init(19, 9, 12, 70, 80, 65);
            //R1B.Init(14, 2, 25,100,200,60);
            //R1SampleHelper.InitDetectChain();
            //PositionCode = 71;
            //mTimerCountDown.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            //{
            //    TimeSpan ts = mdtInStart - DateTime.Now;
            //    if (ts <= TimeSpan.Zero)
            //    {
            //        ServiceProvider.Monitor.ShelfInCountDown = "00:00";
            //        mTimerCountDown.Stop();
            //    }
            //    else
            //    {
            //        ServiceProvider.Monitor.ShelfInCountDown = string.Format("{0:D2}:{1:D2}", ts.Minutes, ts.Seconds);
            //        //ServiceProvider.Monitor.ShelfOutCountDown = string.Format("{0:D2}:{1:D2}", ts.Minutes, ts.Seconds);
            //    }

            //});
            //mTimerCountDown.Interval = 1000;
        }

        public override void Run(Model.ReactionCup cup)
        {
            if (ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].getStatus() == CheckCancelEnum.CANCEL)
            {
                //ServiceProvider.Monitor.DisplayCup[cup.CupSeatID].setStatus(CheckCancelEnum.NOTCAN);

                //ServiceProvider.CupStrip[cup.StripID].Cups[cup.CupSeatID].setStatus(Model.DetectionModel.Cup.CupHoleStatusEnum.EMPTY);
                //ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].CupStatus = "Cancel";
                //return;
            }
            else
            {

                //获取样本信息 及 是否需要添加试剂1 信息

                // cup.SampleInfoID  样本序号   吸样位置
                //cup.StripID  分配的反应条号    加样位置
                // cup.CupSeatID 分配的反应杯号
                // cup.DetectItemModel.reagentName1 通过此数据 获取 试剂1 的位置信息

                //将以上数据 加载到样本列表中

                //等待臂完成加样操作  等待对应 孔位 置状态变化

                Console.WriteLine("加样操作： 样本号：" + cup.SampleInfoID.ToString() + "\r" +
                                              "条号：" + cup.StripID.ToString() + "\r" +
                                              "杯号：" + cup.CupSeatID.ToString() + "\r" +
                                              "试剂1量：" + cup.DetectItemModel.reagentName1.ToString() + "\r" +
                                              "样本量：" + cup.DetectItemModel.bloodAmount.ToString() + "\r");

                ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].CupStatus = "样品添加...";

                ServiceProvider.SampleList.Add(cup); //加入样本执行列表

                //等待样本添加完成
                while (ServiceProvider.CupStrip[cup.StripID].Cups[cup.CupSeatID].getStatus() != Model.DetectionModel.Cup.CupHoleStatusEnum.SAMPLE)
                {
                    Thread.Sleep(100);
                    //取消，两种情况处理，开始添加样本了 直接结束，没开始添加保留
                    if (ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].getStatus() == CheckCancelEnum.CANCEL)
                    {
                        //如果还未分配，从列表中删除此条cup 此步骤可能引起冲突，变化时与ARMcontrol 时间差
                        if (ServiceProvider.CupStrip[cup.StripID].Cups[cup.CupSeatID].getStatus() == Model.DetectionModel.Cup.CupHoleStatusEnum.FULL)
                        {
                            for(int tt =0; tt < ServiceProvider.SampleList.Count;tt++ )
                            {
                                if(ServiceProvider.SampleList.ElementAt(tt).StripID == cup.StripID && ServiceProvider.SampleList.ElementAt(tt).CupSeatID == cup.CupSeatID)
                                    ServiceProvider.SampleList.RemoveAt(tt);
                            }
                            
                            //ServiceProvider.Monitor.DisplayCup[cup.CupSeatID].setStatus(CheckCancelEnum.NOTCAN);

                            //ServiceProvider.CupStrip[cup.StripID].Cups[cup.CupSeatID].setStatus(Model.DetectionModel.Cup.CupHoleStatusEnum.EMPTY);
                            //ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].CupStatus = "Cancel";
                            //return;
                        }
                        else
                        {
                            //ServiceProvider.Monitor.DisplayCup[cup.CupSeatID].setStatus(CheckCancelEnum.NOTCAN);

                            //ServiceProvider.CupStrip[cup.StripID].Cups[cup.CupSeatID].setStatus(Model.DetectionModel.Cup.CupHoleStatusEnum.END);
                            //ServiceProvider.Monitor.DisplayCup[cup.StripID * 4 + cup.CupSeatID].CupStatus = "Cancel";
                            //int gg = 0;
                            //for (int kk = 0; kk < ServiceProvider.CupStrip[cup.StripID].Cups.Count; kk++)
                            //{

                            //    if (ServiceProvider.CupStrip[cup.StripID].Cups[kk].getStatus() == Model.DetectionModel.Cup.CupHoleStatusEnum.END)
                            //        gg++;
                            //    if (gg == 4)
                            //        ServiceProvider.CupStrip[cup.StripID].setStatus(Model.DetectionModel.CupStrip.ReactionStripStatusEnum.UNLOAD);
                            //}
                            //return;
                        }
                        break;
                    }
                }
                
                //mStripID = strip.ID;
                //strip.ReactionStripSeat = ReactionStripStageEnum.ADDREAGENT1_ADDSAMPLE;
                //detectionStatus = ControlStatusEnum.BUSY;//忙碌
                //ServiceProvider.Monitor.R1Position = strip;
                //DetectChainHelper.Position(PositionCode);

                ////R1SampleHelper.RunCup(strip);

                //if (LastCup == null)//第一次倒计时
                //{
                //    mdtInStart = DateTime.Now.AddSeconds(10 * ServiceProvider.Monitor.RunningTestTubeShelf.DetectItemCount);
                //    mTimerCountDown.Start();
                //}
                //AddReagent1AndSample addR1AndSA = new AddReagent1AndSample();
                //for (int i = 0; i < strip.ReactionCupList.Count; i++)
                //{
                //    if (i == 4)
                //        Can.SendCan(Can.SA_MoveA_ID, "1AM40" + Can.strEnd);//滑轨A定位减速度
                //    else
                //        Can.SendCan(Can.SA_MoveA_ID, "1AM18" + Can.strEnd);//滑轨A定位减速度
                //    if (i < 4)
                //    {
                //        addR1AndSA.AddR1AndSA(i, strip.ReactionCupList[i]);
                //        if (i < 3)//第四个不使用此命令
                //        {
                //            Transportation.TransportA.LeftPosition();
                //            Transportation.TransportA.WaitStatus(1);
                //        }
                //    }
                //    else
                //    {

                //        Transportation.TransportA.RightPosition();
                //        Transportation.TransportA.WaitStatus(2);
                //        addR1AndSA.AddR1AndSA(i, strip.ReactionCupList[i]);
                //    }
                //}
                //////向小车添加行动
                //Transportation.AddTransportation(strip, this, NextComponent);
            }
            //下一条链

            NextComponent.Run(cup);
        }
        /// <summary>
        /// 加试剂1和加样本
        /// </summary>
        /// <param name="order">使用的试剂臂</param>
        private void AddR1AndSA(int order, Model.ReactionCup cup)
        {
            // 查找试剂所在试剂盘的孔位
            if (cup.DetectItem != "")
            {
                mReagID = mReagent.GetReagentID(cup.DetectItem, 1);
                if (mReagID > 0)
                {
                    mHoleNum = mReagentKit.GetHoleNumber(mReagID, 1);
                    mHoleNum = 1;//调试用固定为1
                    Kit1.Position(mHoleNum);
                    if (mLastCup != null && mLastCup.SampleInfoID != cup.SampleInfoID)//需要更换试管
                    {
                        if (cup.TestTubeShelfBarcode == mLastCup.TestTubeShelfBarcode)//还在同一个试管架
                        {
                            Sample.WaitStatus(Sample.Position());
                        }
                        else //需要更换试管架 
                        {
                            //    if (ServiceProvider.gReactionStripList.Count > 0)
                            //    {
                            Sample.WaitStatus(Sample.ChangeShelf());
                            Sample.WaitStatus(Sample.Position());
                            mdtInStart = DateTime.Now;

                            ServiceProvider.Monitor.InShelfCount--;
                            ServiceProvider.Monitor.OutShelfCount++;
                            ServiceProvider.Monitor.RunningTestTubeShelf = ServiceProvider.WorkSheetVM.TestTubeShelfList[ServiceProvider.Monitor.OutShelfCount];
                            mdtInStart = DateTime.Now.AddSeconds(10 * ServiceProvider.Monitor.RunningTestTubeShelf.DetectItemCount);
                            mTimerCountDown.Start();

                            //}

                        }
                    }
                    else
                    {

                    }
                    mLastCup = cup;
                    Kit1.WaitStatus(1);
                }
                else
                {
                    DetectChainHelper.PostMessage(3003);
                }
            }
            else
            {
                Random random = new Random();
                Kit1.Position(random.Next(1, 12));
                Kit1.WaitStatus(1);
            }
            //加注
            //if (order % 2 == 0)
            if (true)
            {
                Console.WriteLine(mStripID);
                //if (order != 0)
                //{
                //    //R1A.WaitStatus(3);
                //    //SA.WaitStatus(3);
                //    R1A.RinseInEnd(true);
                //    SA.RinseInEnd(true);
                //}
                while (R1A.ControlStatus != ControlStatusEnum.IDLE || SA.ControlStatus != ControlStatusEnum.IDLE)
                {
                    //Console.WriteLine("aaaa");
                }

                R1A.ControlStatus = ControlStatusEnum.BUSY;

                SA.ControlStatus = ControlStatusEnum.BUSY;

                //试剂1A吸液
                R1A.Imbibe();

                //样本臂SA
                SA.Imbibe();

                R1A.WaitStatus(1);
                R1A.Inject();
                R1A.WaitStatus(2);
                R1A.Rinse();//清洗
                Kit1.Reset();//复位试剂盘

                SA.WaitStatus(1);
                SA.Inject();

                R1A.WaitRinseTime();//持续清洗

                SA.WaitStatus(2);
                SA.Rinse();
                SA.WaitRinseTime();

                Kit1.WaitStatus(0);


            }
            else
            {
                //while (R1B.ControlStatus != ControlStatusEnum.IDLE || SB.ControlStatus != ControlStatusEnum.IDLE)
                //{
                //    //Console.WriteLine("bbbb");
                //}
                R1B.ControlStatus = ControlStatusEnum.BUSY;
                SB.ControlStatus = ControlStatusEnum.BUSY;

                //if (order != 1)
                //{
                //    //R1B.WaitStatus(3);
                //    //SB.WaitStatus(3);
                //    R1B.RinseInEnd(true);
                //    SB.RinseInEnd(true);
                //}

                //试剂1B吸液
                R1B.Imbibe();
                //样本臂SA
                SB.Imbibe();
                R1B.WaitStatus(1);
                R1B.Inject();
                R1B.WaitStatus(2);
                R1B.Rinse();
                Kit1.Reset();//试剂盘复位

                SB.WaitStatus(1);
                SB.Inject();
                R1B.WaitRinseTime();//持续清洗
                SB.WaitStatus(2);
                SB.Rinse();
                SB.WaitRinseTime();
                Kit1.WaitStatus(0);
            }

            //更新显示数据，更新数据库
            ServiceProvider.ReagentKitVM.ReagentKitList[mHoleNum - 1].RemainTimes1--;
            Model.Reagent _reagentModel1 = ServiceProvider.ReagentKitVM.ReagentKitList[mHoleNum - 1].ReagentModel1;
            _reagentModel1.ReagentLeft -= cup.DetectItemModel.reagentAmount1;
            mReagent.Update(_reagentModel1);
        }

        //另一种方法
        private void Run2()
        {

        }
        /// <summary>
        /// 演示方法
        /// </summary>
        /// <param name="strip"></param>
        public override void Simulate(Model.ReactionCup strip)
        {
            //strip.Note = "add reagent1-add sample--" + Thread.CurrentThread.Name + "---" + strip.ID;
            //Console.WriteLine(strip.Note);
            //Thread.Sleep(ServiceProvider.Reagent1SleepTime);
            //detectionStatus = ControlStatusEnum.FINISHED;//完成
        }

        /// <summary>
        /// 工程师调试方法
        /// </summary>
        /// <param name="strip">反应条</param>
        public static void RunEngineer(ReactionStrip strip)
        {
            AddReagent1AndSample addR1AndSA = new AddReagent1AndSample();
            Can.SendCan(Can.SA_MoveA_ID, "1AM100" + Can.strEnd);//滑轨A定位减速度
            Transportation.TransportA.LeftPosition();
            Transportation.TransportA.WaitStatus(1);
            for (int i = 0; i < 8; i++)
            {
                Sample.WaitStatus(Sample.Position());//样本定位

                if (i == 5)
                    Can.SendCan(Can.SA_MoveA_ID, "1AM40" + Can.strEnd);//滑轨A定位减速度
                else
                    Can.SendCan(Can.SA_MoveA_ID, "1AM18" + Can.strEnd);//滑轨A定位减速度
                if (i < 4)
                {
                    addR1AndSA.AddR1AndSA(i, strip.ReactionCupList[i]);
                    if (i < 3)//第四个不使用此命令
                    {
                        Transportation.TransportA.LeftPosition();
                        Transportation.TransportA.WaitStatus(1);
                    }
                }
                else
                {
                    Transportation.TransportA.RightPosition();
                    Transportation.TransportA.WaitStatus(2);
                    addR1AndSA.AddR1AndSA(i, strip.ReactionCupList[i]);
                }
            }
            Sample.WaitStatus(Sample.ChangeShelf());
            Sample.Position();
        }

        /// <summary>
        /// 复位
        /// </summary>
        /// <returns></returns>
        public static bool Reset()
        {
            R1A.Reset();
            R1B.Reset();
            R1A.WaitStatus(0);
            R1B.WaitStatus(0);

            SA.Reset();
            SB.Reset();

            SA.WaitStatus(0);
            SB.WaitStatus(0);

            Kit1.Reset();
            Sample.Reset();
            Transportation.TransportA.Home();


            Kit1.WaitStatus(0);
            Sample.WaitStatus(0);
            Transportation.TransportA.WaitStatus(0);
            return true;
        }
        /// <summary>
        /// 自检
        /// </summary>
        public static void CheckSelf()
        {
            AddReagent1AndSample.Kit1.WaitStatus(AddReagent1AndSample.Kit1.Position(1));
            AddReagent2.Kit2.WaitStatus(AddReagent2.Kit2.Position(1));
            ClearCanalArm(AddReagent1AndSample.SA);
            ClearCanalArm(AddReagent1AndSample.SB);
            ClearCanalArm(AddReagent1AndSample.R1A);
            ClearCanalArm(AddReagent1AndSample.R1B);
        }

        private static void ClearCanalArm(Communication.ArmControl arm)
        {
            arm.WaitStatus(arm.Imbibe(0));
            arm.WaitStatus(arm.Inject());
            arm.WaitStatus(arm.Rinse());
            arm.WaitClearCanal();
        }
        /// <summary>
        /// 暂停
        /// </summary>
        public static void Pause(bool isPause)
        {
            _isPause = isPause;
            R1A.IsPause = isPause;
            R1B.IsPause = isPause;
            SA.IsPause = isPause;
            SB.IsPause = isPause;
            Kit1.IsPause = isPause;
            Sample.IsPause = isPause;
        }


        #region // 模块运行控制，Anry
        private void RunControl(ReactionStrip strip)
        {
            string sendCmd = "";    // 发送命令
            int reagID = 0;         // 试剂编号
            byte holeNum = 0;       // 孔位编号
            Clipper.Model.ReagentKit reagKit = new Model.ReagentKit();      // 试剂盘对象
            Clipper.Model.DetectItems detItem = new Model.DetectItems();    // 检测项对象 


            for (int i = 0; i < strip.ReactionCupList.Count; i++)
            {
                #region // 将相应的样本移到吸样位
                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }
                // 如果样本系统状态为空闲，则将相应的样本移动到吸样位
                if (mStatusSS == ControlStatusEnum.IDLE)
                {
                    sendCmd = mArmSS.LocateSampleShelf(strip.ReactionCupList[i].TestTubeShelfBarcode,
                                                       strip.ReactionCupList[i].TestTubeHoleNumber);
                    Can.SendDataToCan(Convert.ToInt16(mArmSS), sendCmd);
                    mStatusSS = ControlStatusEnum.BUSY;
                }
                mArmSS.CompleteReset.WaitOne();

                #endregion // 将相应的样本移到吸样位

                #region // 将试剂盘1转到相应位置
                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 如果试剂盘1空闲，将试剂盘1转到指定位置，将试剂盘状态设置为忙
                if (mStatusDish1 == ControlStatusEnum.IDLE)
                {
                    // 查找试剂所在试剂盘的孔位
                    reagID = mReagent.GetReagentID(strip.ReactionCupList[i].DetectItem, 1);
                    holeNum = mReagentKit.GetHoleNumber(reagID, 1);
                    sendCmd = mArmR1A.LocateReagentDish(holeNum);
                    Can.SendDataToCan(Convert.ToInt16(mArmR1A.CanID), sendCmd);
                    mStatusDish1 = ControlStatusEnum.BUSY;
                }
                else
                {
                    // 处理异常，程序退出
                }

                #endregion // 将试剂盘1转到相应位置

                #region // 反应杯进给：滑轨A将反应条相应杯传送到加试剂1的位置
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 如果滑轨A空闲,则它将反应条下一个杯移到加试剂1位置
                if (ServiceProvider.gStatusSlideA == ControlStatusEnum.IDLE)
                {
                    Transportation.AssayCupFeeding('A', (byte)(i + 1));
                    ServiceProvider.gStatusSlideA = ControlStatusEnum.BUSY;
                }

                // 等待滑轨A到位
                while (ServiceProvider.gStatusSlideA == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }

                // 等待试剂盘1到位
                while (mStatusDish1 == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }

                // 等待样本到位
                while (mStatusSS == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }
                #endregion // 反应杯进给：滑滑轨A将反应条相应杯传送到加试剂1的位置

                #region // 吸试剂1：R1A或R1B吸试剂1
                // 如果R1A空闲，则使用臂R1A
                if (mStatusR1A == ControlStatusEnum.IDLE)
                {
                    mUsingReagentArm = mArmR1A;
                }
                // 如果R1B空闲，则使用臂R1B
                else if (mStatusR1B == ControlStatusEnum.IDLE)
                {
                    mUsingReagentArm = mArmR1B;
                }
                else
                {
                    // 处理异常，程序退出
                }

                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                reagKit = mReagentKit.GetModel(holeNum);                                // 获得试剂盘对象
                detItem = mDetectItem.GetModel(strip.ReactionCupList[i].DetectItem);    // 获得检查项对象

                // 如果试剂盘1转到位，且滑轨A空闲
                if (mStatusDish1 == ControlStatusEnum.IDLE && ServiceProvider.gStatusSlideA == ControlStatusEnum.IDLE)
                {
                    // 如果剩余试剂量够用，则吸试剂，将当前臂的状态设置为忙
                    if (reagKit.ReagentModel1.ReagentLeft > detItem.reagentAmount1)
                    {
                        sendCmd = mUsingReagentArm.Aspirate(detItem.reagentAmount1);            // 生成吸试剂命令
                        Can.SendDataToCan(Convert.ToInt16(mUsingReagentArm.CanID), sendCmd);    // 发送吸试剂命令
                        reagKit.ReagentModel1.ReagentLeft -= detItem.reagentAmount1;                         // 记录当前试剂量
                        mReagentKit.Update(reagKit);                                            // 更新数据库内容
                        mStatusUsingReagentArm = ControlStatusEnum.BUSY;                            // 设置臂状态为忙
                    }
                    else
                    {
                        // 弹出界面，提醒用户更换试剂
                        // 暂停本模块的运行
                        // 更换完成之后，再转到试剂剩余量的判断
                    }
                }
                #endregion // 吸试剂1：R1A或R1B吸试剂1

                #region // 吸样本：SA或SB吸样本
                // 如果样本臂A空闲，则使用它
                if (mStatusSA == ControlStatusEnum.IDLE)
                {
                    mUsingSampleArm = mArmSA;
                }
                else if (mStatusSB == ControlStatusEnum.IDLE)
                {
                    mUsingSampleArm = mArmSB;
                }
                else
                {
                    // 异常处理
                }

                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 如果样本臂空闲，且样本系统空闲，则吸样本
                if (mStatusUsingSampleArm == ControlStatusEnum.IDLE && mStatusSS == ControlStatusEnum.IDLE)
                {
                    sendCmd = mUsingSampleArm.Aspirate(detItem.bloodAmount);
                    Can.SendDataToCan(Convert.ToInt16(mUsingSampleArm.CanID), sendCmd);
                    mStatusUsingSampleArm = ControlStatusEnum.BUSY;
                }
                else
                {
                    // 异常处理
                }
                #endregion // 吸样本：SA或SB吸样本

                #region // 加试剂1：R1A或R1B加试剂1
                // 等待吸试剂1完成
                while (mStatusUsingReagentArm == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }

                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 如果R1B吸试剂1完成，且反应杯到位，则加试剂,将当前臂的状态设置为忙
                if (mStatusUsingReagentArm == ControlStatusEnum.IDLE && ServiceProvider.gStatusSlideA == ControlStatusEnum.IDLE)
                {
                    sendCmd = mUsingReagentArm.Dispense();
                    Can.SendDataToCan(Convert.ToInt16(mUsingReagentArm.CanID), sendCmd);
                    mStatusUsingReagentArm = ControlStatusEnum.BUSY;
                }

                // 等待加试剂完成
                while (mStatusUsingReagentArm == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }
                #endregion // 加试剂1：R1A或R1B加试剂1

                #region // 加样本：SA或SB加样本
                // 等待吸样本完成
                while (mStatusUsingSampleArm == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }

                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 如果加试剂1完成，样本臂空闲，则加样本
                if (mStatusUsingReagentArm == ControlStatusEnum.IDLE && mStatusUsingSampleArm == ControlStatusEnum.IDLE)
                {
                    sendCmd = mUsingSampleArm.Dispense();
                    Can.SendDataToCan(Convert.ToInt16(mUsingSampleArm.CanID), sendCmd);
                    mStatusUsingSampleArm = ControlStatusEnum.BUSY;
                }
                #endregion // 加样本：SA或SB加样本

                #region // 清洗试剂针
                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 条件：加试剂1完成,且清洗液的量够用
                if (mStatusUsingReagentArm == ControlStatusEnum.IDLE)
                {
                    sendCmd = mUsingReagentArm.RinseNeedle();
                    Can.SendDataToCan(Convert.ToInt16(mUsingReagentArm.CanID), sendCmd);
                    mStatusUsingReagentArm = ControlStatusEnum.BUSY;
                }
                #endregion // 清洗试剂针

                #region // 清洗样本针
                // 等待加样本完成
                while (mStatusUsingSampleArm == ControlStatusEnum.BUSY)
                {
                    System.Threading.Thread.Sleep(ServiceProvider.gInteralmSec);
                }

                // 如果模块需要暂停，则暂停模块运行，等待外部改变此状态且继续模块运行
                if (IsPause)
                {
                    mPause.WaitOne();
                }

                // 条件：加样本完成,且清洗液的量够用
                if (mStatusUsingSampleArm == ControlStatusEnum.IDLE)
                {
                    sendCmd = mUsingSampleArm.RinseNeedle();
                    Can.SendDataToCan(Convert.ToInt16(mUsingSampleArm.CanID), sendCmd);
                    mStatusUsingSampleArm = ControlStatusEnum.BUSY;
                }
                #endregion // 清洗样本针
            }
        }
        #endregion // 模块运行控制，Anry
    }
}

